<template>
  <div>
    <a-button @click="getDevices" type="primary">123</a-button>
    <div ref="wrapRef" :style="{ height, width }"></div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, nextTick, unref, onMounted } from 'vue';
  import { useScript } from '@/hooks/web/useScript';

  defineOptions({ name: 'BaiduMap' });

  defineProps({
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: 'calc(100vh - 78px)',
    },
  });

  const wrapRef = ref<HTMLDivElement | null>(null);
  const { toPromise: toPromise1 } = useScript({
    src: 'https://api.map.baidu.com/getscript?v=3.0&ak=rU8qkC216C0zEXnKTeKYHzubOHFzowRL&services=&t=20210201100830&s=1',
  });
  const { toPromise: toPromise2 } = useScript({
    src: 'https://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js',
  });
  const { toPromise: toPromise3 } = useScript({
    src: 'https://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js',
  });

  async function listAllDevice() {
    return fetch('http://localhost:8787/listAllLatLng').then((res) => {
      return res.json();
    });
  }

  let BMap;

  async function initMap() {
    await toPromise1();
    await toPromise2();
    await toPromise3();
    await nextTick();
    const wrapEl = unref(wrapRef);
    if (!wrapEl) return;
    BMap = (window as any).BMap;
    const map = new BMap.Map(wrapEl);
    const point = new BMap.Point(114.0545429, 22.5445741);
    map.centerAndZoom(point, 1);
    map.enableScrollWheelZoom(true);
    // const marker = new BMap.Marker(point); // 创建标注
    // map.addOverlay(marker);
    return map;
  }

  function getDevices() {
    listAllDevice().then((res) => {
      let set = new Set<string>();
      res.forEach((item) => {
        if (!set.has('' + item.lng + item.lat)) {
          set.add('' + item.lng + item.lat);
          const point = new BMap.Point(parseFloat(item.lng), parseFloat(item.lat));
          console.log(point);
          const marker = new BMap.Marker(point); // 创建标注
          map.addOverlay(marker);
        }
      });
    });
  }

  let map;

  onMounted(async () => {
    map = await initMap();
  });
</script>
